﻿using NuGet.Common;
using NuGet.Configuration;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.Packaging.Signing;
using NuGet.Protocol.Core.Types;
using NuGet.Versioning;

namespace FrameworkCore.Helpers;

public class NuGetHelper
{
    public static async Task<string> DownloadAndExtractPackage(string packageId, string version, string targetDirectory)
    {
        // 1. 设置 NuGet 源
        var providers = new List<Lazy<INuGetResourceProvider>>();
        providers.AddRange(Repository.Provider.GetCoreV3());
        var sourceRepositoryProvider = new SourceRepositoryProvider(new PackageSourceProvider(Settings.LoadDefaultSettings(root: null)), providers);

        // 2. 创建 NuGet 包标识
        var packageIdentity = new PackageIdentity(packageId, NuGetVersion.Parse(version));

        // 3. 创建下载上下文
        var downloadContext = new SourceCacheContext();
        var logger = NullLogger.Instance;
        var cancellationToken = CancellationToken.None;

        // 4. 获取 NuGet 设置和全局包文件夹
        var settings = Settings.LoadDefaultSettings(root: null);
        var globalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(settings);

        // 5. 获取下载资源
        var sourceRepository = sourceRepositoryProvider.CreateRepository(new PackageSource("https://api.nuget.org/v3/index.json")); // NuGet 官方源
        var downloadResource = await sourceRepository.GetResourceAsync<DownloadResource>();

        // 6. 下载 NuGet 包
        var downloadResult = await downloadResource.GetDownloadResourceResultAsync(
            packageIdentity,
            new PackageDownloadContext(downloadContext, targetDirectory, false),
            globalPackagesFolder, // 使用 globalPackagesFolder
            logger,
            cancellationToken);

        // 7. 检查下载状态
        if (downloadResult.Status != DownloadResourceResultStatus.Available)
        {
            throw new Exception($"Failed to download package: {packageId} {version}. Status: {downloadResult.Status}");
        }

        // 8. 解压 NuGet 包
        var packageFilePath = Path.Combine(globalPackagesFolder, packageIdentity.Id, packageIdentity.Version.ToString(), $"{packageIdentity.Id}.{packageIdentity.Version}.nupkg");

        // 确保目标目录存在
        Directory.CreateDirectory(targetDirectory);

        using (var packageStream = new FileStream(packageFilePath, FileMode.Open, FileAccess.Read))
        {
            // 创建 ClientPolicyContext 实例
            var clientPolicyContext = ClientPolicyContext.GetClientPolicy(settings, logger);

            var extractionContext = new PackageExtractionContext(
                PackageSaveMode.Defaultv3,
                XmlDocFileSaveMode.None,
                clientPolicyContext,
                logger);

            // 使用 ExtractPackageAsync 方法提取包
            var packagePathResolver = new PackagePathResolver(targetDirectory);
            var extractedFiles = await PackageExtractor.ExtractPackageAsync(
                "NuGet Source", // 可以是源的名称
                packageStream,
                packagePathResolver,
                extractionContext,
                cancellationToken);
        }

        return targetDirectory;
    }
}
